<?php
class sfWidgetFormDateWithWeek extends sfWidgetFormDate  {

    protected function configure($options = array(), $attributes = array())
    {
        parent::configure($options , $attributes );
        $this->addOption('format', '%week%/%month%/%year%');
        $this->addOption('weeks', parent::generateTwoCharsRange(1, 5));
        $this->addOption('empty_values', array('year' => '', 'month' => '', 'week' => ''));
    }


    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        // convert value to an array
        
        //print_r($value);exit;
        
        $default = array('year' => null, 'month' => null, 'week' => null);
        if ( is_array($value) && count($value) == 2 && strtotime($value[0]))
        {
            $w = dateRangeToWeekNumber($value);
            $first_date_time = strtotime($value[0]);
            $y = date( 'Y',$first_date_time );
            $m = date( 'm' , $first_date_time );
            $value = array('year' => $y, 'month' => $m, 'week' => $w);

        }elseif(is_array($value)){
            $value = array_merge($default,$value);
        }else{
            $value = $default;
        }


        $date = array();
        $emptyValues = $this->getOption('empty_values');

        $date['%week%'] = $this->renderWeekWidget($name.'[week]', $value['week'], array('choices' => $this->getOption('can_be_empty') ? array('' => $emptyValues['week']) + $this->getOption('weeks') : $this->getOption('weeks')), array_merge($this->attributes, $attributes));
        $date['%month%'] = $this->renderMonthWidget($name.'[month]', $value['month'], array('choices' => $this->getOption('can_be_empty') ? array('' => $emptyValues['month']) + $this->getOption('months') : $this->getOption('months')), array_merge($this->attributes, $attributes));
        $date['%year%'] = $this->renderYearWidget($name.'[year]', $value['year'], array('choices' => $this->getOption('can_be_empty') ? array('' => $emptyValues['year']) + $this->getOption('years') : $this->getOption('years')), array_merge($this->attributes, $attributes));


        return strtr($this->getOption('format'), $date);
    }


    protected function renderWeekWidget($name, $value, $options, $attributes)
    {
        $widget = new sfWidgetFormSelect($options, $attributes);
        return $widget->render($name, $value);
    }


}